/**
 * 根据path 返回菜单的展开项和选中项
 * @param tree
 * @param path
 * @returns {*}
 */
export function findMenuByPath(tree, path) {
  let arr = [];
  formatData(tree, 0);
  function formatData(tree, level = 0, parentId = "") {
    level++;
    for (let i in tree) {
      let treePath = tree[i].id + "";
      if (parentId) {
        treePath = `${parentId}-${treePath}`;
      }
      arr.push({ ...tree[i], level: level, parentId: treePath });
      if (tree[i].children) {
        formatData(tree[i].children, level, tree[i].id);
      }
    }
  }
  let obj = arr.find((item) => item.path === path);
  // 这里的id变成字符串了得转数字
  let parentIds = obj.parentId.split("-").map((item) => item * 1);
  let result = {
    opens: [],
    selected: [],
  };
  result.selected = [parentIds[parentIds.length - 1]];
  if (parentIds.length > 1) {
    result.opens = parentIds.slice(0, parentIds.length - 1);
  }
  return result;
}

/**
 * 树结构转列表结构
 * @param tree
 * @param result
 * @param level
 * @returns {*[]}
 */
export function treeToList(tree, result = [], level = 0) {
  tree.forEach((node) => {
    if (node.path) {
      result.push(node);
    }
    node.level = level + 1;
    node.children && treeToList(node.children, result, node.level);
  });
  return result;
}

export function getAssetsFile(url) {
  return new URL(`../assets/images/${url}`, import.meta.url).href;
}

/**
 * 根据对象某个属性进行排序
 * @param arr 原数组
 * @param key 属性名
 * @returns {*}
 */
export function objArrSort(arr, key) {
  try {
    const compare = function (obj1, obj2) {
      let val1 = obj1[key] * 1 || 0;
      let val2 = obj2[key] * 1 || 0;
      if (val1 < val2) {
        return -1;
      } else if (val1 > val2) {
        return 1;
      } else {
        return 0;
      }
    };
    return arr.sort(compare);
  } catch (err) {
    console.log("err", arr);
  }
}

/**
 * 随机生成n-m之间的整数
 * @param n
 * @param m
 * @returns {*|number}
 */
export function getRandomInt(n, m) {
  let r = Math.random();
  r = r * (m - n + 1);
  r = Math.floor(r);
  r = r + n;
  return r;
}

/**
 * 随机获取颜色
 * @returns {string}
 */
export function getRandomColor() {
  const letters = "0123456789ABCDEF";
  let color = "#";
  for (let i = 0; i < 6; i++) {
    color += letters[Math.floor(Math.random() * 16)];
  }
  return color;
}
/**
 * 随机获取颜色
 * @returns {string}
 */
export function getDarkRandomColor() {
  const letters = "0123456789ABCDEF";
  let color = "#";
  let redFactor = 0.5; // 在0.3到0.8之间选择一个随机数作为红色比例
  for (let i = 0; i < 6; i++) {
    if (i < 3) {
      // 前三个字符为红色（R、G、B）
      color += letters[Math.floor(Math.random() * (16 * redFactor))];
    } else {
      // 后三个字符为绿色和蓝色（G、B）
      color += letters[Math.floor(Math.random() * 16)];
    }
  }
  return color;
}

/**
 * 移动数组元素
 * @param arr 原数组
 * @param index
 * @param direction 为负前移n位 为正后移位
 * @returns {*[]}
 */
export function moveArrEl(arr = [], index = 0, direction = 0) {
  // 检查索引是否在数组范围内
  if (index < 0 || index >= arr.length || typeof direction !== "number") {
    return arr;
  }

  // 根据方向确定新的索引
  let newIndex;
  if (direction > 0) {
    newIndex = index + direction;
    // 如果当前元素是数组的最后一个元素，则无法向后移动
    if (newIndex >= arr.length) {
      newIndex = arr.length - 1;
    }
  } else if (direction < 0) {
    newIndex = index + direction;
    // 如果当前元素是数组的第一个元素，则无法后退
    if (newIndex < 0) {
      newIndex = 0;
    }
  }

  // 交换当前元素和新位置的元素
  let temp = arr[index];
  arr[index] = arr[newIndex];
  arr[newIndex] = temp;
  return arr;
}

/**
 * 读取文件返回base64
 * @param file
 * @returns {Promise<unknown>}
 */
export function getBase64(file) {
  return new Promise((resolve, reject) => {
    const reader = new FileReader();
    reader.readAsDataURL(file);
    reader.onload = () => resolve(reader.result);
    reader.onerror = (error) => reject(error);
  });
}

/**
 * 一维数组转二位数组
 * @param array 原数组
 * @param chunkSize 每个子数组的长度
 * @returns {*[]}
 */
export function chunkArray(array, chunkSize) {
  const results = [];
  for (let i = 0; i < array.length; i += chunkSize) {
    const chunk = array.slice(i, i + chunkSize);
    results.push(chunk);
  }
  return results;
}
